<template>
  <div class="login_container">
    <div class="login_box">
      <div class="avatar">
        <img src="../assets/wyz.jpg" alt />
      </div>
      <!-- 登录表单 -->
      <el-form
        label-width="0px"
        :model="formData"
        :rules="formRules"
        ref="loginForm"
        status-icon
        hide-required-asterisk
      >
        <el-form-item prop="username">
          <el-input prefix-icon="el-icon-user" v-model="formData.username"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input prefix-icon="el-icon-lock" v-model="formData.password" show-password></el-input>
        </el-form-item>
        <el-form-item class="btns">
          <el-button type="primary" @click="login('loginForm')">登录</el-button>
          <el-button @click="reset('loginForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  name: 'login',
  data() {
    return {
      formData: {
        username: 'admin',
        password: '123456'
      },
      formRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 16, message: '长度在 6 到 16 个字符', trigger: ['blur', 'change'] }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  methods: {
    reset(formName) {
      this.$refs[formName].resetFields()
    },
    login(formName) {
      this.$refs[formName].validate(async boolean => {
        if (!boolean) return false
        const { data } = await this.$http.post('login', this.formData)
        if (data.meta.status !== 200) {
          return this.$message.error('登录失败:' + data.meta.msg + '!')
        }
        this.$message.success('登录成功!')
        window.sessionStorage.setItem('token', data.data.token)
        this.$router.push('/home')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.login_container {
  position: relative;
  width: 100%;
  height: 100%;
  background-color: #2b4b6b;
}
.login_box {
  position: absolute;
  left: 50%;
  top: 50%;
  width: 450px;
  height: 300px;
  background-color: #fff;
  transform: translate(-50%, -50%);
}
.avatar {
  position: absolute;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 130px;
  height: 130px;
  background-color: #fff;
  border-radius: 50%;
  padding: 10px;
  border: 1px solid #eee;
  img {
    width: 100%;
    height: 100%;
    border-radius: 50%;
  }
}
.el-form {
  position: absolute;
  bottom: 0;
  width: 100%;
  padding: 20px;
  box-sizing: border-box;
  .btns {
    display: flex;
    justify-content: flex-end;
  }
}
</style>
